/*
 * PersistenceUtil.java
 *
 * Created on August 12, 2007, 11:46 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package tcc.util;

import javax.persistence. EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
/**
 *
 * @author Diego
 */
public class PersistenceUtil {
    
    public static final String persistenceUnit = "EstoquePU";
    private EntityManagerFactory emf;
    
    private static PersistenceUtil instance;
    
    private PersistenceUtil() {
        try{
            this.emf = Persistence.createEntityManagerFactory(PersistenceUtil.persistenceUnit);
        }catch(Throwable t){
            throw new ExceptionInInitializerError(t);
        }
    }
    
    public synchronized static PersistenceUtil getInstance() {
        if (instance == null){
            instance  = new PersistenceUtil();
        }
        return instance;
    }
    
    public EntityManager getEntityManager() {
        ThreadLocal<EntityManager> t = new ThreadLocal<EntityManager>();
        if(t.get()==null){
            t.set(this.emf.createEntityManager());
        }
        return t.get();
    }
    public void disposeEntityManager(){
        ThreadLocal<EntityManager> t = new ThreadLocal<EntityManager>();
        if(t.get()!=null){
            t.get().close();
            t.equals(null);
        }
    }
    
    public EntityTransaction getTransaction(){
        return this.getEntityManager().getTransaction();
        
        
    }
}
